import React, { Component } from 'react'
import { connect } from 'react-redux'
import Todo from 'es6!./Todo'
import { addTodo, toggleTodo } from 'es6!../actions/index'

class TodoList extends Component {

  state = {
    value: ''
  }

  addTodo = () => {
    this.props.dispatch(addTodo(this.state.value))
    this.setState({
      value: ''
    })
  }

  handleChange = e => {
    this.setState({
      value: e.target.value
    })
  }

  render() {
    const { todos, dispatch } = this.props;

    return (
      <div>
        <ul>
          {todos.map(todo => (
            <Todo key={todo.id} {...todo} onClick={() => dispatch(toggleTodo(todo.id))} />
          ))}
        </ul>

        <form className="form-inline">
          <div className="form-group">
            <input className="form-control" value={this.state.value} onChange={this.handleChange} />
          </div>
          <button className="btn btn-default" onClick={this.addTodo}>add</button>
        </form>
      </div>
    )
  }
}

const mapStateToProps = state => ({
  todos: state.todos
})

export default connect(mapStateToProps)(TodoList)